package com.zuosh.common;

import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Created by zuosh on 2017/4/2.
 */
@Configuration
public class WebSecurityConfig extends WebMvcConfigurerAdapter {
    public static final String SESSION_KEY = "user";

    @Bean
    public SecurityInterceptor getSecurityInterceptor() {
        return new SecurityInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        InterceptorRegistration addInterceptor = registry.addInterceptor(getSecurityInterceptor());
        //要排除的配置
        addInterceptor.excludePathPatterns("/sys/error");
        addInterceptor.excludePathPatterns("/sys/login**");
        //要拦截的配置
        addInterceptor.addPathPatterns("/sys/**");
    }

    private class SecurityInterceptor extends HandlerInterceptorAdapter {
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
                throws Exception {
            System.out.println("CHECK::======" + request.getRequestURI() + "==" + request.getRequestURL());
            System.out.println("LIST[COOKIE]=======");
            Cookie[] cookies = request.getCookies();
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    System.out.println(cookie.getName() + "==" + cookie.getValue());
                }
            }
            //如果
            if (cookies == null) {
                Cookie cookie = new Cookie("isLogin", "no");
                response.addCookie(cookie);
            }
            ////
            HttpSession session = request.getSession();
            if (session.getAttribute(SESSION_KEY) != null) {
                return true;
            }
            // 跳转登录
            String url = "/sys/login";
            response.sendRedirect(url);
            return false;
        }
    }
}
